package com.it.demo.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class WxController {


    /**
     * 二维码页面
     * @return
     */
    @RequestMapping("wx/connect/qrconnect")
    public String qrCode(){
        return "qrconnect";
    }

    /**
     * 用户授权页面
     * @return
     */
    @RequestMapping("/wx/confirm")
    public String confirm(){
        return "confirm";
    }

    /**
     * 用户确认授权
     * @return
     */
    @GetMapping("/wx/pass")
    public String pass(String appid, String redirect_uri, Model model){
        String appSecret = "87wjef4453deg432";
        String code = "abc"; //模拟临时票据
        //通过 app_id, app_secret 和 code 获取接口调用凭证 access_token 和  授权用户唯一标识 openid
        String getAccessTokenURLFormat = "http://localhost:8080/wx/sns/oauth2/access_token?appid={}&secret={}&code={}&grant_type=authorization_code";
        String getAccessTokenURL = StrUtil.format(getAccessTokenURLFormat, appid,appSecret,code);

        //通过 hutool 工具类 访问url
        String tokenResponse = HttpUtil.get(getAccessTokenURL);
        //通过 hutool 工具类 转换为 json 对象
        JSONObject tokenJson= JSONUtil.parseObj(tokenResponse);

        //获取json 对象相关字段
        Integer errcode = (Integer)tokenJson.get("errcode");
        String errmsg = (String)tokenJson.get("errmsg");
        String openid = (String)tokenJson.get("openid");            //微信用户的唯一标识，可以跟自己数据库的用户进行关联
        String access_token = (String)tokenJson.get("access_token"); //作用是获取该微信用户的具体信息

        model.addAttribute("openid",openid);
        model.addAttribute("access_token",access_token);

        return redirect_uri;
    }

    /**
     * 模拟获取AccessToken
     * @return
     */
    @GetMapping("/wx/sns/oauth2/access_token")
    @ResponseBody
    public String getAccessToken(String appid,String secret,String code){
        JSONObject json = new JSONObject();
        json.set("errcode",null);
        json.set("errmsg",null);
        json.set("openid","666");
        json.set("access_token","&HG^FUI");

        return json.toString();
    }

}
